package com.yl.chainStore.services.impl

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.entity.customer.CustomerInfo
import com.yl.chainStore.entity.sick.CustomerSubscribeLog
import com.yl.chainStore.entity.sick.SickCustomerAccessLog
import com.yl.chainStore.entity.sick.SickMedicalRecordsDetail
import com.yl.chainStore.entity.user.CompanyUserCustomerSelectLog
import com.yl.chainStore.entity.warehouse.*
import com.yl.chainStore.mapper.customer.CustomerInfoMapper
import com.yl.chainStore.mapper.sick.CustomerSubscribeLogMapper
import com.yl.chainStore.mapper.sick.SickCustomerAccessLogMapper
import com.yl.chainStore.mapper.sick.SickMedicalRecordsDetailMapper
import com.yl.chainStore.mapper.user.CompanyUserCustomerSelectLogMapper
import com.yl.chainStore.mapper.user.CompanyUserOperationLogMapper
import com.yl.chainStore.mapper.warehouse.*
import com.yl.chainStore.pojo.vo.customer.CustomerSelectVo
import com.yl.chainStore.pojo.vo.sick.CustomerSubscribeLogSelectVo
import com.yl.chainStore.pojo.vo.sick.SickCustomerAccessLogSelectVo
import com.yl.chainStore.pojo.vo.sick.SickMedicalRecordsDetailSelectVo
import com.yl.chainStore.pojo.vo.user.CompanyUserCustomerSelectLogSelectVo
import com.yl.chainStore.pojo.vo.user.CompanyUserOperationLogSelectVo
import com.yl.chainStore.pojo.vo.user.RegisteredUserResult
import com.yl.chainStore.services.ICustomerInfoService
import com.yl.chainStore.services.IWebCompanyUserService
import com.yl.chainStore.services.sick.ICustomerSubscribeLogService
import com.yl.chainStore.util.dayFormat
import com.yl.chainStore.util.getDays
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.common.enum.UserPackageTypeEnum
import com.yl.users.entity.CompanyUser
import com.yl.users.services.ICompanyUserService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*

@Service
class WebCompanyUserServiceImpl(
	private val warehouseInOrderMapper: WarehouseInOrderMapper,
	private val warehouseOutOrderMapper: WarehouseOutOrderMapper,
	private val warehouseDispatchOrderMapper: WarehouseDispatchOrderMapper,
	private val warehouseCheckOrderMapper: WarehouseCheckOrderMapper,
	private val warehouseProfitLossOrderMapper: WarehouseProfitLossOrderMapper,
	private val customerInfoMapper: CustomerInfoMapper,
	private val customerSubscribeLogMapper: CustomerSubscribeLogMapper,
	private val sickMedicalRecordsDetailMapper: SickMedicalRecordsDetailMapper,

	private val companyUserCustomerSelectLogMapper: CompanyUserCustomerSelectLogMapper,

	private val companyUserOperationLogMapper: CompanyUserOperationLogMapper,

	private val sickCustomerAccessLogMapper: SickCustomerAccessLogMapper
) : IWebCompanyUserService {

	@Autowired
	lateinit var iCustomerSubscribeLogService: ICustomerSubscribeLogService

	@Autowired
	lateinit var iCompanyUserService: ICompanyUserService

	@Autowired
	lateinit var iCustomerInfoService:ICustomerInfoService

	companion object {
		private val log = LoggerFactory.getLogger(IWebCompanyUserService::class.java)
	}

	override fun stagingInOrder(inOrder: WarehouseInOrder): ResponseBody {
		log.info("用户操作 ==> 暂存入库单:inorder:{}", inOrder)
		if (inOrder.orderTime == null) {
			inOrder.orderTime = Date()
		}
		if (inOrder.inUserId == null) {
			inOrder.inUserId = inOrder.createUserId
		}
		log.info("用户业务逻辑 ==> 添加一个入库单草稿：inOrder{}", inOrder)
		inOrder.status = Status.STAGING
		warehouseInOrderMapper.insert(inOrder)
		return returnSuccess()
	}

	override fun getStagingInOrder(userId: Long, warehouseId: Long): WarehouseInOrder? {
		log.info("用户操作 ==> 取出暂存入库单:userId:{}，warehouseId{}", userId, warehouseId)
		val list = warehouseInOrderMapper.getUserStagingInOrder(userId, warehouseId, Status.STAGING)
		if (list.isEmpty()) {
			return null
		}
		return list[0]
	}

	override fun stagingOutOrder(outOrder: WarehouseOutOrder): ResponseBody {
		log.info("用户操作 ==> 暂存出库单:outOrder:{}", outOrder)
		if (outOrder.orderTime == null) {
			outOrder.orderTime = Date()
		}
		if (outOrder.outUserId == null) {
			outOrder.outUserId = outOrder.createUserId
		}
		outOrder.status = Status.STAGING
		warehouseOutOrderMapper.insert(outOrder)
		return returnSuccess()
	}

	override fun getStagingOutOrder(userId: Long, warehouseId: Long): WarehouseOutOrder? {
		log.info("用户操作 ==> 取出暂存出库单:userId:{}，warehouseId{}", userId, warehouseId)
		val userStagingOutOrder = warehouseOutOrderMapper.getUserStagingOutOrder(userId, warehouseId, Status.STAGING)
		if (userStagingOutOrder.isEmpty()) {
			return null
		}
		return userStagingOutOrder[0]
	}

	override fun stagingDispatchOrder(dispatchOrder: WarehouseDispatchOrder): ResponseBody {
		log.info("用户操作 ==> 暂存调度单:outOrder:{}", dispatchOrder)
		if (dispatchOrder.orderTime == null) {
			dispatchOrder.orderTime = Date()
		}
		dispatchOrder.inStatus = Status.STAGING
		dispatchOrder.outStatus = Status.STAGING
		warehouseDispatchOrderMapper.insert(dispatchOrder)
		return returnSuccess()
	}

	override fun getStagingDispatchOrder(userId: Long, warehouseId: Long): WarehouseDispatchOrder? {
		log.info("用户操作 ==> 取出暂存调度单:userId:{}，warehouseId{}", userId, warehouseId)
		val userStagingDispatchOrder =
			warehouseDispatchOrderMapper.getUserStagingDispatchOrder(userId, warehouseId, Status.STAGING)
		if (userStagingDispatchOrder.isEmpty()) {
			return null
		}
		return userStagingDispatchOrder[0]
	}

	override fun stagingCheckOrder(checkOrder: WarehouseCheckOrder): ResponseBody {
		log.info("用户操作 ==> 暂存盘点单:checkOrder:{}", checkOrder)
		checkOrder.status = Status.STAGING
		warehouseCheckOrderMapper.insert(checkOrder)
		return returnSuccess()
	}

	override fun getStagingCheckOrder(userId: Long, warehouseId: Long): WarehouseCheckOrder? {
		log.info("用户操作 ==> 取出暂存盘点单:userId:{}，warehouseId{}", userId, warehouseId)
		val orderList =
			warehouseCheckOrderMapper.getUserStagingCheckOrder(userId, warehouseId, Status.STAGING)
		if (orderList.isEmpty()) {
			return null
		}
		return orderList[0]
	}


	override fun stagingPlOrder(order: WarehouseProfitLossOrder): ResponseBody {
		log.info("用户操作 ==> 暂存损益单:order:{}", order)
		order.status = Status.STAGING
		warehouseProfitLossOrderMapper.insert(order)
		return returnSuccess()
	}

	override fun getStagingPlOrder(userId: Long, warehouseId: Long): WarehouseProfitLossOrder? {
		log.info("用户操作 ==> 取出暂存损益单:userId:{}，warehouseId{}", userId, warehouseId)
		val orderList =
			warehouseProfitLossOrderMapper.getUserStagingOrder(userId, warehouseId, Status.STAGING)
		if (orderList.isEmpty()) {
			return null
		}
		return orderList[0]
	}

	override fun getSelfCustomerPage(page: Page<CustomerInfo>, vo: CustomerSelectVo): Page<CustomerInfo> {
		log.info("用户操作 ==> 我的客户分页:vo:{}", vo)
		if (vo.userId == null) {
			vo.userId = getContext().userId
		}
		if(vo.companyId == null){
			vo.companyId = getContext().companyId
		}
		val resPage = customerInfoMapper.selectUserCustomerPage(page, vo,vo.userId!!,vo.companyId!!)
		for(info in resPage.records){
			info.showRules = iCustomerInfoService.getShowRuleByOrderDetail(info.id,vo.deptId?: getContext().subCompanyId)
		}
		return resPage
	}

	override fun getSubscribeLogList(vo: CustomerSubscribeLogSelectVo): List<CustomerSubscribeLog> {
		if(vo.subCompanyId == null){
			vo.subCompanyId = getContext().subCompanyId
		}
		if(vo.subLogType == null){
			vo.subLogType = TypeEnum.CUSTOMER_SUBSCRIBE_TYPE_NORMAL
		}
		val subscribeLogList = customerSubscribeLogMapper.getSubscribeLogList(vo)
		for (subLog in subscribeLogList) {
			if (subLog.itemIdsShow != null) {
				subLog.itemNames = iCustomerSubscribeLogService.getSubscribeItemsByIdsStr(subLog.itemIdsShow!!)
			}
		}
		return subscribeLogList
	}

	override fun getSubscribeLogPage(vo: CustomerSubscribeLogSelectVo): Page<CustomerSubscribeLog> {
		if(vo.subCompanyId == null){
			vo.subCompanyId = getContext().subCompanyId
		}
		if(vo.subLogType == null){
			vo.subLogType = TypeEnum.CUSTOMER_SUBSCRIBE_TYPE_NORMAL
		}
		val subscribeLogPage = customerSubscribeLogMapper.getSubscribeLogPage(
			Page(vo.current,vo.size),vo)
		for (subLog in subscribeLogPage.records) {
			if (subLog.itemIdsShow != null) {
				subLog.itemNames = iCustomerSubscribeLogService.getSubscribeItemsByIdsStr(subLog.itemIdsShow!!)
			}
		}
		return subscribeLogPage
	}

	override fun getSubScribeListByDate(
		userId: Long,
		vo: CustomerSubscribeLogSelectVo
	): MutableList<MutableList<CustomerSubscribeLog>> {
		val user = iCompanyUserService.getUser(userId) ?: return mutableListOf()
		return getSubScribeListByDate(user, vo)
	}

	override fun getSubScribeListByDate(
		user: CompanyUser,
		vo: CustomerSubscribeLogSelectVo
	): MutableList<MutableList<CustomerSubscribeLog>> {
		val resList = mutableListOf<MutableList<CustomerSubscribeLog>>()
		when (user.userWorkType) {
			UserPackageTypeEnum.COMPANY_USER_TYPE_DOCTOR -> {
				vo.doctorId = user.id
			}
			UserPackageTypeEnum.COMPANY_USER_TYPE_NURSE -> {
				vo.nurseId = user.id
			}
			UserPackageTypeEnum.COMPANY_USER_TYPE_CONSULT -> {
				vo.consultantId = user.id
			}
			else->{

			}
		}
		if (vo.type.equals("day")) {
			//查询单个开始日期,直接返回
			if (vo.beginTime == null) {
				vo.beginTime = dayFormat(Date())
			}
			resList.add(customerSubscribeLogMapper.getSubscribeLogList(vo))
		} else {
			if (vo.beginTime != null && vo.endTime != null) {
				//对查询到得数组进行处理
				val daysList = getDays(vo.beginTime!!, vo.endTime!!)
				for (i in daysList) {
					vo.beginTime = i
					vo.type = "day"
					resList.add(customerSubscribeLogMapper.getSubscribeLogList(vo))
				}
			}
		}
		return resList
	}

	override fun getTodayNewAddSubCount(userId: Long): Int {
		return customerSubscribeLogMapper.getDoctorTodayNewSub(userId)
	}

	override fun getUserStatusResult(user: CompanyUser, userType: UserPackageTypeEnum): RegisteredUserResult {
		//护士和前台没做
		val res =  RegisteredUserResult(
		id = user.id,
		name = user.realName,

		)
		when(userType){
			UserPackageTypeEnum.COMPANY_USER_TYPE_DOCTOR->{
				val selectUserRecordsDetailCount = sickMedicalRecordsDetailMapper.selectUserRecordsDetailCount(
					SickMedicalRecordsDetailSelectVo(
						doctorId = user.id,
						day = Date(),
						statuses = listOf(Status.WAIT_AUDIT, Status.IN_THE_TREATMENT)
					)
				)
				res.status =  if(selectUserRecordsDetailCount != 0){
					res.waitCount = selectUserRecordsDetailCount
					Status.CONSULTING

				}else{
					Status.FREE
				}
				return res
			}
			UserPackageTypeEnum.COMPANY_USER_TYPE_NURSE->{

			}
			UserPackageTypeEnum.COMPANY_USER_TYPE_CONSULT->{
				val selectUserRecordsDetailCount = sickMedicalRecordsDetailMapper.selectUserRecordsDetailCount(
					SickMedicalRecordsDetailSelectVo(
						secondaryUserId = user.id,
						day = Date(),
						statuses = listOf(Status.WAIT_AUDIT, Status.IN_THE_TREATMENT)
					)
				)
				res.status =  if(selectUserRecordsDetailCount != 0){
					res.waitCount = selectUserRecordsDetailCount
					Status.CONSULTING

				}else{
					Status.FREE
				}
				return res

			}
			UserPackageTypeEnum.COMPANY_USER_TYPE_FRONT_DESK->{

			}
			else->{

			}
		}
		return res
	}

	override fun getRecordDetailPage(
		userId: Long,
		page: Page<SickMedicalRecordsDetail>,
		vo: SickMedicalRecordsDetailSelectVo
	): Page<SickMedicalRecordsDetail> {
		if (vo.doctorId == null) {
			vo.doctorId = userId
		}
		return sickMedicalRecordsDetailMapper.getPage(page, vo)
	}

	override fun addSelectCustomerLog(selectLog: CompanyUserCustomerSelectLog): ResponseBody {

		val selectList = companyUserCustomerSelectLogMapper.selectList(
			Wrappers.query<CompanyUserCustomerSelectLog?>().eq("user_id", selectLog.userId)
				.eq("customer_id", selectLog.customerId)
		)
		if (selectList.isEmpty()) {
			companyUserCustomerSelectLogMapper.insert(selectLog)
		} else {
			companyUserCustomerSelectLogMapper.update(
				null,
				Wrappers.update<CompanyUserCustomerSelectLog?>().eq("user_id", selectLog.userId)
					.eq("customer_id", selectLog.customerId).set("select_time", selectLog.selectTime)
			)
		}

		return returnSuccess()
	}

	override fun getSelectCustomerLogPage(
		vo: CompanyUserCustomerSelectLogSelectVo
	): Page<CompanyUserCustomerSelectLog> {
		if (vo.userId == null) {
			vo.userId = getContext().userId
		}

		return companyUserCustomerSelectLogMapper.selectUserLogPage(Page(vo.current, vo.size), vo)
	}

	override fun deleteSelectCustomerLog(userId: Long?, customerId: Long?): ResponseBody {
		if(userId == null && customerId == null){
			return returnError(ErrorCode.PARAM_EMPTY,"请传入参数")
		}
		val delWrappers = QueryWrapper<CompanyUserCustomerSelectLog>()
		if(userId != null){
			delWrappers.eq("user_id",userId)
		}
		if(customerId != null){
			delWrappers.eq("customer_id",customerId)
		}
		companyUserCustomerSelectLogMapper.delete(delWrappers)
		return returnSuccess()
	}

	override fun getVisitCountToday(userId: Long): Int {
		return sickCustomerAccessLogMapper.getTodayNewAccessLogByUserId(userId)
	}

	override fun getUpdateLogCountByVo(vo: CompanyUserOperationLogSelectVo): Int {
		return companyUserOperationLogMapper.selectCountByVo(vo)
	}

	override fun getFollowLogList(userId:Long,vo: SickCustomerAccessLogSelectVo): List<SickCustomerAccessLog> {
		log.info("客户操作：==>获取随访列表数据：vo:{}", vo)
		vo.type = TypeEnum.ACCESS_LOG_FOLLOW_UP
		vo.userId = userId
		return sickCustomerAccessLogMapper.getLogList( vo)

	}

	override fun getFollowLogPage(userId:Long,vo: SickCustomerAccessLogSelectVo): Page<SickCustomerAccessLog> {
		log.info("用户操作：==>获取随访分页数据：vo:{}", vo)
		vo.type = TypeEnum.ACCESS_LOG_FOLLOW_UP
		vo.userId = userId
		return sickCustomerAccessLogMapper.getLogPage(Page(vo.current,vo.size), vo)
	}
}
